package com.cskaoyan.user.service.impl;

import com.cskaoyan.mall.commons.constant.AddressConstant;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.RegisterCodeResponse;
import com.cskaoyan.user.form.UserRegisterRequest;
import com.cskaoyan.user.form.UserVerifyRequest;
import com.cskaoyan.user.service.IUserRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author: 杨庆
 * @since: 2022.9.19 22:34
 * @description:
 */
@Service
@Slf4j
public class IUserRegisterServiceImpl implements IUserRegisterService {

    @Autowired
    MemberMapper memberMapper;
    @Autowired
    UserVerifyMapper userVerifyMapper;
    @Autowired
    JavaMailSender javaMailSender;

    @Override
    public RegisterCodeResponse register(UserRegisterRequest request) {
        RegisterCodeResponse registerCodeResponse = new RegisterCodeResponse();
        //TODO 判断用户是否已经存在
        Example example = new Example(Member.class);
        example.createCriteria()
                .andEqualTo("username",request.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(members)){
            throw new ValidateException(UserRetCode.USERNAME_ALREADY_EXISTS.getCode(),UserRetCode.USERNAME_ALREADY_EXISTS.getMessage());
        }
        //TODO 1 向用户表中插入一条记录
        Member member = new Member();
        member.setEmail(request.getEmail());
        member.setUsername(request.getUserName());
        //TODo 密码的加密 md5   加密的登录时候需要加密equlas
        String pwd = DigestUtils.md5DigestAsHex(request.getUserPwd().getBytes());
        member.setPassword(pwd);
        //member.setPassword(request.getUserPwd());
        member.setCreated(new Date());
        member.setUpdated(new Date());
        member.setIsVerified("N");
        member.setState(1);
        int affectRows = memberMapper.insertSelective(member);
        if (affectRows != 1) {
            registerCodeResponse.setCode(UserRetCode.USER_REGISTER_FAILED.getCode());
            registerCodeResponse.setMessage(UserRetCode.USER_REGISTER_FAILED.getMessage());
            return  registerCodeResponse;
        }
        //TODO 2 向用户验证表中插入一条记录
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(member.getUsername());
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        userVerify.setUuid(uuid);
        userVerify.setIsVerify("N");
        userVerify.setIsExpire("N");
        userVerify.setRegisterDate(new Date());
        int row = userVerifyMapper.insertSelective(userVerify);
        if (row != 1) {
            registerCodeResponse.setCode(UserRetCode.USER_REGISTER_VERIFY_FAILED.getCode());
            registerCodeResponse.setMessage(UserRetCode.USER_REGISTER_VERIFY_FAILED .getMessage());
            return  registerCodeResponse;
        }
        //TODO 发送用户激活邮件
        Sendmail(uuid,request);
        //打印日式
        log.info("注册成功");
        registerCodeResponse.setCode(UserRetCode.SUCCESS.getCode());
        registerCodeResponse.setMessage(UserRetCode.SUCCESS.getMessage());
        return registerCodeResponse;
    }
    /**
    * @description: 邮件的发送
    [uuid, email]
    * @return: void
    * @author: 杨庆
    * @time: 2022.9.20 21:49
     */
    private void Sendmail(String uuid, UserRegisterRequest request) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom("13526091932@163.com");
        simpleMailMessage.setTo(request.getEmail());
        simpleMailMessage.setSubject("账号的激活");
        StringBuilder stringBuilder = new StringBuilder();
        //stringBuilder.append("http://127.0.0.1:8080/user/verify?uuid=")
        stringBuilder.append(AddressConstant.EMAILL_ADDRESS)
                .append(uuid).append("&username=")
                .append(request.getUserName());
        simpleMailMessage.setText(stringBuilder.toString());
        javaMailSender.send(simpleMailMessage);
    }

    @Override
    public RegisterCodeResponse verify(UserVerifyRequest request) {
        RegisterCodeResponse registerCodeResponse = new RegisterCodeResponse();
        //TODO 修改用户表的isverify
        Member member = new Member();
        member.setIsVerified("Y");
        member.setUpdated(new Date());
        Example example = new Example(Member.class);
        example.createCriteria()
                .andEqualTo("username",request.getUsername());
        int affectRows = memberMapper.updateByExampleSelective(member, example);
        if (affectRows != 1) {
            registerCodeResponse.setCode(UserRetCode.VERIFY_UPDATE_MEMBER.getCode());
            registerCodeResponse.setMessage(UserRetCode.VERIFY_UPDATE_MEMBER.getMessage());
            return registerCodeResponse;
        }
        //TODO 修改认证表
        UserVerify userVerify = new UserVerify();
        userVerify.setIsVerify("Y");
        Example example1 = new Example(UserVerify.class);
        example1.createCriteria()
                .andEqualTo("uuid",request.getUuid());
        int affectRows2 = userVerifyMapper.updateByExampleSelective(userVerify, example1);
        if (affectRows != 1) {
            registerCodeResponse.setCode(UserRetCode.VERIFY_UPDATE_VERIFYMEMBER.getCode());
            registerCodeResponse.setMessage(UserRetCode.VERIFY_UPDATE_VERIFYMEMBER.getMessage());
            return registerCodeResponse;
        }
        //TODO 成功
        registerCodeResponse.setCode(UserRetCode.SUCCESS.getCode());
        registerCodeResponse.setMessage(UserRetCode.SUCCESS.getMessage());
        return registerCodeResponse;
    }
}
